/// Author: Samle
import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart';
import 'package:memorize_words/db/db_serializer.dart';

import '../../../../db/db_helper.dart';
import '../../../../store/setting_store.dart';
import '../controllers/books_controller.dart';

/// 特殊自定义组件
import '../../../../util/SearchFence.dart';
import '../../../../util/books_list_view.dart';

class BooksView extends GetView<BooksController> {

  SettingStore _settingStore = SettingStore();

  void checkDel(context,value) async {
    Get.defaultDialog(
      title: '确认删除？',
      radius: 10.0,
      barrierDismissible: false,
      content: const Text("请确认是否删除该条数据！"),
      confirm: MaterialButton(
        color: Colors.black,
        textColor: Colors.white,
        child: const Text('确认', style: TextStyle(fontSize: 18.0,fontWeight: FontWeight.w600)),
        onPressed: () async {
          await controller.delBooks(value);
          Get.back();
          controller.onInit();
        },
      ),
      cancel: MaterialButton(
        color: Colors.white,
        textColor: Colors.black87,
        child: const Text('取消', style: TextStyle(fontSize: 18.0,fontWeight: FontWeight.w600)),
        onPressed: () {
          Get.back();
        },
      ),
    );
  }

  void checkDownload(context,value) async {
    Get.defaultDialog(
      title: '确认缓存？',
      radius: 10.0,
      barrierDismissible: false,
      content: const Text("当前操作将缓存该字典词汇，请确认是否进行缓存！"),
      confirm: MaterialButton(
        color: Colors.black,
        textColor: Colors.white,
        child: const Text('确认', style: TextStyle(fontSize: 18.0,fontWeight: FontWeight.w600)),
        onPressed: () async {
          Get.back();
          controller.itemslong.value = 1;
          controller.itemsInedx.value = 0;
          _showCircularDialog2("${value['name']} 获取中……");
          await controller.getWords(value['path'],value['id']);
          Get.back();
          Fluttertoast.showToast(
            msg: "缓存成功！",
            toastLength: Toast.LENGTH_SHORT,
            gravity: ToastGravity.BOTTOM,
            backgroundColor: Colors.green,
            textColor: Colors.white,
            fontSize: 16.0,
          );
          // controller.onInit();
        },
      ),
      cancel: MaterialButton(
        color: Colors.white,
        textColor: Colors.black87,
        child: const Text('取消', style: TextStyle(fontSize: 18.0,fontWeight: FontWeight.w600)),
        onPressed: () {
          Get.back();
        },
      ),
    );
  }

  void checkSelected(context,item) async {
    Get.defaultDialog(
      title: '确认选中？',
      radius: 10.0,
      barrierDismissible: false,
      content: const Text("当前操作将替换选中词典，是否确认？"),
      confirm: MaterialButton(
        color: Colors.black,
        textColor: Colors.white,
        child: const Text('确认', style: TextStyle(fontSize: 18.0,fontWeight: FontWeight.w600)),
        onPressed: () async {
          Get.back();
          _showCircularDialog("设置中……");
          List words = await localData.getWordsBySearch({"belong":',' + item['id'].toString() + ','});
          Get.back();
          print(words.length);
          if (words.isNotEmpty) {
            int bookSelected = await _settingStore.getBookSelected();
            /// 如果当前选中和历史选中不一致，则存储当前选中
            if (bookSelected != item['id']){
              await _settingStore.setBookSelected(item['id']);
              await _settingStore.setWordSelected(0);
            }
            Map wordSelected = await localData.getCurrentWord(item['id'],0);
            print(wordSelected);
            // Map bookSelected = await localData.getBooksById(bookSelectedId);
            Fluttertoast.showToast(
              msg: "选中" + item['name'],
              toastLength: Toast.LENGTH_SHORT,
              gravity: ToastGravity.BOTTOM,
              backgroundColor: Colors.green,
              textColor: Colors.white,
              fontSize: 16.0,
            );
            Get.back(result: true);
            Get.offNamed('/home');
            // await Get.toNamed('/home', preventDuplicates: false);

          } else {
            Fluttertoast.showToast(
              msg: "请先缓存数据再进行操作！",
              toastLength: Toast.LENGTH_SHORT,
              gravity: ToastGravity.BOTTOM,
              backgroundColor: Colors.red,
              textColor: Colors.white,
              fontSize: 16.0,
            );
          }
        },
      ),
      cancel: MaterialButton(
        color: Colors.white,
        textColor: Colors.black87,
        child: const Text('取消', style: TextStyle(fontSize: 18.0,fontWeight: FontWeight.w600)),
        onPressed: () {
          Get.back();
        },
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        // leading: controller.bookSelected.value != 0 ? IconButton(
        //   icon: const Icon(Icons.density_medium_sharp),
        //   onPressed: (){
        //     Get.offNamed('/home');
        //   },
        // ):null,
        elevation: 0,
        backgroundColor: Colors.black87,
        title: const Text('词典'),
        centerTitle: true
      ),
      body: Container(
        decoration: const BoxDecoration(color: Colors.white),
        child:ConstrainedBox(                          /// 约束盒子
          constraints: const BoxConstraints.expand(),  /// 不指定高和宽时则铺满整个屏慕
          child: Stack(
            alignment:Alignment.center ,               /// 指定对齐方式为居中
            children: <Widget>[                        /// 子组件列表
              controller.obx((state) => Center(
                child: controller.booksList.value.isNotEmpty?
                /// MyListView 是一个自定义的列表显示组件
                /// https://blog.csdn.net/weixin_40929065/article/details/123797218
                BooksListView(
                  datas: controller.booksList.value,
                  onPressed: (item) async {
                    // print(item);
                    // print("点击查看");
                    checkSelected(context,item);
                  },
                  doublePressed: (item) {
                    // print(item);
                    // print("双击编辑");
                    if (item['source'] == 'default') {
                      Fluttertoast.showToast(
                        msg: "默认资源不允许编辑！",
                        toastLength: Toast.LENGTH_SHORT,
                        gravity: ToastGravity.BOTTOM,
                        backgroundColor: Colors.red,
                        textColor: Colors.white,
                        fontSize: 16.0,
                      );
                    } else {
                      controller.dataForm = item;
                      controller.toEditPage();
                    }
                  },
                  longPressed: (item) {
                    // print(item);
                    // print("长按删除");
                    if (item['source'] == 'default') {
                      Fluttertoast.showToast(
                        msg: "默认资源不允许删除！",
                        toastLength: Toast.LENGTH_SHORT,
                        gravity: ToastGravity.BOTTOM,
                        backgroundColor: Colors.red,
                        textColor: Colors.white,
                        fontSize: 16.0,
                      );
                    } else {
                      checkDel(context,item);
                    }
                  },
                  onTap: (id) async {
                    Map book = await localData.getBooksById(id);
                    print(book);
                    checkDownload(context,book);
                  },
                  toDetail: (id) {
                    Get.toNamed('/words', arguments: {"bookId":id});
                    // ?.then((value) async { controller.onInit();});
                  },
                  dropdown: () { controller.getBooksList(); },
                  pullup: () { controller.getBooksListMore(); },
                )
                    :const Text("暂无记录"),
              )),
              Positioned(
                top: 0.0,
                child:
                /// MySearchFence 是一个自定义的搜索组件
                /// https://blog.csdn.net/weixin_40929065/article/details/123638686
                SearchFence(
                  onSearch:(value){ controller.search.text = value; controller.getBooksList(); },
                  hasRightIcon: false,
                  rightIcon: Icons.flip,
                  onIcon:(value){ controller.search.text = value; controller.getBooksList(); },
                  onChange: (value) { controller.search.text = value; controller.getBooksList(); },
                  onClean: (value) { controller.search.text = value; controller.getBooksList(); },
                ),
              ),
            ],
          ),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        // backgroundColor: Colors.transparent,
        backgroundColor: Colors.white70,
        foregroundColor: Colors.black87,
        elevation: 0,
        onPressed: () {controller.toEditPage();},
        child: const Icon(Icons.post_add_outlined),
      ),
    );
  }

  _showCircularDialog(String content) {
    return showDialog(
      barrierDismissible: false,
      context: Get.context!,
      builder: (context) => AlertDialog(
        content: Container(
          height: 100,
          child: Column(
            children: <Widget>[
              CupertinoActivityIndicator(radius: 30),
              SizedBox(height: 10.0),
              Text(content),
            ],
          ),
        ),
      ),
    );
  }
  _showCircularDialog2(String content) {
    return showDialog(
      barrierDismissible: false,
      context: Get.context!,
      builder: (context) => AlertDialog(
        content: Container(
          height: 110,
          child: Column(
            children: <Widget>[
              Text(content),
              SizedBox(height: 10.0),
              Obx(()=>Container(
                decoration: BoxDecoration(
                  border: Border.all(color: Colors.blueAccent, width: 0.5),
                  color: Colors.white,
                  borderRadius: BorderRadius.circular((5.0)),
                  boxShadow: [BoxShadow(color: Colors.blueGrey, offset: Offset(1.0, 1.0), blurRadius: 1.0, spreadRadius: 1.0), ],
                ),
                width: 200,
                height: 20,
                child: Align(
                  alignment: Alignment.centerLeft,
                  child: Container(
                    decoration: BoxDecoration(
                      border: Border.all(color: Colors.blueAccent, width: 0.5),
                      color: Colors.blueAccent,
                      borderRadius: BorderRadius.circular((5.0)),
                      // boxShadow: [BoxShadow(color: Colors.lightGreen, offset: Offset(1.0, 1.0), blurRadius: 1.0, spreadRadius: 1.0), ],
                    ),
                    width: 200 * ((controller.itemsInedx.value / controller.itemslong.value * 10000 ~/ 1)/10000),
                    height: 20,
                  ),
                ),
              ),),
              SizedBox(height: 10.0),
              Obx(()=>Text(((controller.itemsInedx.value / controller.itemslong.value * 10000 ~/ 1)/100).toString() + '%')),
            ],
          ),
        ),
      ),
    );
  }
}
